/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-7-17 下午1:21 Created by dwzhang
 */
package com.jade.bss.web.controller;

import javax.servlet.http.HttpServletResponse;
import com.jade.bss.base.customer.Customer;
import com.jade.bss.customer.grant.GrantManager;
import com.jade.bss.security.shiro.authc.CustomerPasswordToken;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.base.lang.StatusException;
import com.jade.framework.base.util.ResponseUtils;
import com.jade.framework.cache.CacheService;
import com.jade.framework.cache.CacheUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户登录控制器，与AdminLoginController不能同时部署在一个Context中。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-7-17 下午1:21
 */
@RestController
@Api(value = "用户登录")
public class CustomerLoginController
{
    protected Log logger = LogFactory.getLog(this.getClass());

    @RequestMapping (value = "/login", method = RequestMethod.POST)
    @ApiOperation(value = "登录", httpMethod = "POST")
    public void login(@RequestParam (value = "username") String username, @RequestParam (value = "password") String password,  HttpServletResponse response)
            throws Exception
    {
        try {
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated())
            {
                CustomerPasswordToken token = new CustomerPasswordToken();
                token.setType(Customer.DEFAULT_TYPE);
                token.setUsername(username);
                token.setPassword(password.toCharArray());
                subject.login(token);
                this.logger.info(username + " login");
            }
        }
        catch (Exception ex) {
            logger.error("auth error:", ex);
            ResponseUtils.writeErrorResult(response,201,"","登录失败，请检查用户名和密码");
        }
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        customer.setUid(SecurityUtils.getSubject().getSession().getId().toString());
        customer.setPushId(customer.getUid());
        ResponseUtils.writeSuccessResult(response,customer);
    }

    @RequiresAuthentication
    @RequestMapping (value = "/getSessionId", method = RequestMethod.GET)
    @ApiOperation(value = "会话编号", httpMethod = "GET")
    public String getSessionId(HttpServletResponse response)  throws Exception
    {
        return SecurityUtils.getSubject().getSession().getId().toString();
    }

    @RequiresAuthentication
    @RequestMapping (value = "/getInfo", method = RequestMethod.GET)
    @ApiOperation(value = "用户信息", httpMethod = "GET")
    public void getInfo(HttpServletResponse response)  throws Exception
    {
        ResponseUtils.writeSuccessResult(response, SecurityUtils.getSubject().getPrincipal());
    }

    @RequiresAuthentication
    @RequestMapping (value = "/logout", method = RequestMethod.POST)
    @ApiOperation(value = "用户退出", httpMethod = "POST")
    public void logout(HttpServletResponse response)  throws Exception
    {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        ResponseUtils.writeSuccessResult(response);
    }

    public static final String CACHE_KEY_PERM = "security.perms";
    protected String systemName = "nb-bss";
    protected CacheService cacheService = ApplicationContextUtils.getBean("system_cacheService");
    @RequiresAuthentication
    @RequestMapping (value = "/getRole", method = RequestMethod.GET)
    @ApiOperation(value = "操作权限", httpMethod = "GET")
    public void getMenu(HttpServletResponse response)  throws Exception
    {
        Customer customer= (Customer) SecurityUtils.getSubject().getPrincipal();
        List<String> permissions = cacheService.get(CacheUtils.joinKey(systemName, CACHE_KEY_PERM, String.valueOf(customer.getId())));
        ResponseUtils.writeSuccessResult(response, permissions);
    }
}
